<template>
  <div class="app-container">
    <!--条件搜索表单-->
    <el-row>
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="searchObj.name" placeholder="文件原始名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="getAll()">查询</el-button>
          <el-button icon="el-icon-refresh" @click="reset()">清空</el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <!-- 工具栏 -->
    <el-row class="toolbar-row">
      <el-upload
        class="toolbar-item"
        :show-file-list="false"
        :action="uploadUrl"
        :headers="uploadHeaders"
        :before-upload="handleBeforeUpload"
        :on-success="handleSuccess"
      >
        <el-button icon="el-icon-upload" type="primary">上传 </el-button>
      </el-upload>

      <el-button
        v-if="hasPerm('sys:file:batch-delete')"
        class="toolbar-item"
        type="danger"
        icon="el-icon-delete"
        :disabled="ids.length < 1"
        @click="batchDelete"
      >
        批量删除
      </el-button>
    </el-row>

    <el-table
      v-loading="loading"
      element-loading-text="正在努力加载数据中..."
      :data="page.records"
      :border="true"
      stripe
      style="width: 100%; margin: 15px 0px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" fixed="left" width="55" />
      <el-table-column type="index" fixed="left" width="80" label="序号" />
      <el-table-column prop="name" fixed="left" label="文件名称" min-width="120" sortable show-overflow-tooltip />
      <el-table-column prop="originalName" label="原始名称" min-width="120" sortable show-overflow-tooltip />
      <el-table-column prop="type" label="文件类型" min-width="120" show-overflow-tooltip />
      <el-table-column prop="size" label="文件大小" min-width="120" sortable show-overflow-tooltip>
        <template v-slot="{ row }">
          {{ formatSize(row.size) }}
        </template>
      </el-table-column>
      <el-table-column prop="path" label="访问路径" min-width="120" show-overflow-tooltip>
        <template v-slot="{ row }">
          <el-link :href="row.path">{{ row.path }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" min-width="120" sortable show-overflow-tooltip />

      <!-- 操作 -->
      <el-table-column label="操作" width="150" fixed="right" align="center">
        <template slot-scope="scope">
          <el-link v-if="hasPerm('sys:file:download')" type="primary" icon="el-icon-download" @click="handleDownload(scope.row)">下载</el-link>
          <el-divider v-if="hasPerm('sys:file:delete')" direction="vertical" />
          <el-link v-if="hasPerm('sys:file:delete')" type="danger" icon="el-icon-remove" @click="remove(scope.row.id)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页导航栏 -->
    <div>
      <el-pagination
        :background="true"
        :current-page="pIndex"
        :page-size="pSize"
        :total="page.total"
        :page-sizes="[1, 3, 6, 9, 12, 15, 18]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        @current-change="getAll"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script>
// 引入api接口定义的js文件
import fileApi from '@/api/sys/file'
import { downloadFile, formatFileSize } from '@/utils'
import { getToken } from '@/utils/auth'

export default {
  data() {
    // 定义变量和初始值
    return {
      loading: false, // 加载状态
      pIndex: 1, // 当前页
      pSize: 6, // 每页显示记录数
      searchObj: {}, // 条件封装对象
      page: [], // 列表
      visible: false, // 表单显示
      ids: [],

      uploadUrl: process.env.VUE_APP_BASE_API + '/sys/file/upload',
      uploadHeaders: { Authorization: `Bearer ${getToken()}` }
    }
  },
  created() {
    this.getAll()
  },
  methods: {
    formatSize(byte) {
      return formatFileSize(byte)
    },
    // 加载列表数据
    getAll(current = 1) {
      this.loading = true
      this.pIndex = current
      fileApi
        .getPage(this.pIndex, this.pSize, this.searchObj)
        .then((response) => {
          this.page = response.data
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 复选框选中
    handleSelectionChange(r) {
      // 得到选中的id
      this.ids = r.map((v) => v.id)
    },

    // 改变页码
    handleSizeChange(pageSize) {
      this.pSize = pageSize
      // 重新调用数据加载方法 --> 方法中已经加入的查询参数
      this.getAll()
    },

    // 删除
    remove(id) {
      this.$confirm('此操作将永久删除参数信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        fileApi.deleteById(id).then((resp) => {
          this.$message.success('删除成功!')
          this.getAll()
        })
      })
    },

    // 处理下载
    handleDownload(row) {
      fileApi
        .download(row.name)
        .then((res) => {
          downloadFile(res)
        })
        .catch(() => {
          this.$message.error('文件下载失败')
        })
    },

    // 处理上传前
    handleBeforeUpload(file) {
      const isLt9M = file.size / 1024 / 1024 < 10

      if (!isLt9M) {
        this.$message.error('上传头像图片大小不能超过 10MB!')
      }

      return isLt9M
    },

    // 处理上传成功
    handleSuccess(res) {
      if (res.code === 200) {
        this.$message.success('文件上传成功')
        this.getAll()
      } else {
        this.$message.error(res.message)
      }
    },

    // 批量删除
    batchDelete() {
      if (this.ids.length > 0) {
        this.$confirm('此操作将永久删除参数信息,是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          // 确定执行then方法
          .then(() => {
            fileApi.batchDelete(this.ids).then((resp) => {
              this.$message.success('删除成功！')
              this.getAll()
            })
          })
          .catch(() => {})
      } else {
        this.$message.warning('至少选择一条数据!')
      }
    },

    // 重置
    reset() {
      this.searchObj = {}
      this.getAll()
    }
  }
}
</script>

<style scoped>
.toolbar-row {
  margin-bottom: 15px;
}

.toolbar-item {
  display: inline-block;
  margin-right: 10px;
}
</style>
